package com.example.travel.controller;


import com.example.travel.pojo.Category;
import com.example.travel.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("admin/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("list")
    public String getAllInfo(Model model){

        List<Category> categoryList = categoryService.getAllInfo();

        model.addAttribute("list",categoryList);

        return "category/list";
    }

    //添加数据
    @RequestMapping("add")
    public String add(@RequestParam("cname") String cName){

        Category category = new Category();
        category.setCname(cName.trim());

        int flag = categoryService.addInfo(category);
        if (flag >= 1){
            return "redirect:list";
        }else {
            return "error";
        }
    }

    //通过id获得原本信息
    @RequestMapping("getInfo/{cid}")
    public String getInfo(@PathVariable("cid") Integer cId,
                          Model model){

        Category info = categoryService.getInfo(cId);

        model.addAttribute("info",info);

        return "category/edit";
    }

    //更新
    @RequestMapping("update")
    public String update(@RequestParam("cid") Integer cId,
                         @RequestParam("cname") String cName){

        Category category = new Category();
        category.setCid(cId);
        category.setCname(cName);

        int flag = categoryService.update(category);
        if (flag >= 1){
            return "redirect:list";
        }else {
            return "error";
        }

    }

    //删除
    @RequestMapping("delete/{cid}")
    public int delete(@PathVariable("cid") Integer cId){

        return categoryService.delete(cId);
    }
}
